package com.flst.sql.db;

import java.util.ArrayList;
import java.util.List;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.flst.entity.Promotion;
import com.flst.sql.MaBaseSQLite;
import com.flst.sql.PromotionDao;

public class PromotionDaoDb implements PromotionDao{
	
	private SQLiteDatabase base;

	private static final String TABLE = "T_Promotion";
	private static final String COL_ID = "ID";
	private static final String COL_NOM = "NOM";
	private static final String COL_EFFECTIF = "EFFECTIF";
	
	public PromotionDaoDb(MaBaseSQLite bdd) {
		base = bdd.getReadableDatabase();
	}

	@Override
	public List<Promotion> getAllPromotion() {
		List<Promotion> list_promotions = new ArrayList<Promotion>();

		Cursor c = base.query(TABLE, new String[] { COL_ID, COL_NOM,
				COL_EFFECTIF }, null, null, null, null, null);

		if (c.moveToFirst()) {
			do {
				list_promotions.add(cursorToPromotion(c));
			} while (c.moveToNext());
		}
		c.close();

		return list_promotions;
	}
	
	@Override
	public Promotion getPromotionByNom(String nom) {
		Promotion promotion = new Promotion();
		
		Cursor c = base.query(TABLE, new String[] { COL_ID, COL_NOM,
				COL_EFFECTIF }, COL_NOM + " like '%" + nom + "%'", null, null, null, null);

		if (c.moveToFirst()) {
			do {
				promotion = cursorToPromotion(c);
			} while (c.moveToNext());
		}
		c.close();
		
		return promotion;
	}
	
	public Promotion cursorToPromotion(Cursor c) {
		Promotion promotion = new Promotion();

		promotion.setId(c.getLong(0));
		promotion.setNom(c.getString(1));
		promotion.setEffectif(c.getInt(2));

		return promotion;
	}

	@Override
	public Promotion getPromotionById(Long id_promotion) {
		Promotion promotion =  new Promotion();
		
		Cursor c = base.query(TABLE, new String[] { COL_ID, COL_NOM,
				COL_EFFECTIF }, COL_ID + " =" + id_promotion , null, null, null, null);

		if (c.moveToFirst()) {
			do {
				promotion = cursorToPromotion(c);
			} while (c.moveToNext());
		}
		c.close();
		
		return promotion;
	}
	
}
